//
//  XMScanCodeViewController.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/6/3.
//

#import "XMScanCodeViewController.h"
#import "XMScanCodeView.h"
#import "XMScanCodeObc.h"

@interface XMScanCodeViewController () {
    XMScanCodeObc *scanCode;
}

@property (nonatomic, strong) XMScanCodeView *scanView;
@property (nonatomic, strong) UIButton *flashlightBtn;
@property (nonatomic, strong) UILabel *promptLabel;
@property (nonatomic, assign) BOOL isSelectedFlashlightBtn;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation XMScanCodeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    /// 二维码开启方法
    [scanCode startRunningWithBefore:^{
        
    } completion:^{
        
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.scanView startScanning];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.scanView stopScanning];
    [self removeFlashlightBtn];
    [scanCode stopRunning];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor clearColor];
    [self creatUI];
}

- (void)dealloc {

    [self removeScanningView];
}

#pragma mark - Method
- (void)removeScanningView {
    [self.scanView stopScanning];
    [self.scanView removeFromSuperview];
    self.scanView = nil;
}
#pragma mark - - - 闪光灯按钮
- (UIButton *)flashlightBtn {
    if (!_flashlightBtn) {
        // 添加闪光灯按钮
        _flashlightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        CGFloat flashlightBtnW = 30;
        CGFloat flashlightBtnH = 30;
        CGFloat flashlightBtnX = 0.5 * (self.view.frame.size.width - flashlightBtnW);
        CGFloat flashlightBtnY = 0.55 * self.view.frame.size.height;
        _flashlightBtn.frame = CGRectMake(flashlightBtnX, flashlightBtnY, flashlightBtnW, flashlightBtnH);
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightOpenImage"] forState:(UIControlStateNormal)];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightCloseImage"] forState:(UIControlStateSelected)];
        [_flashlightBtn addTarget:self action:@selector(flashlightBtn_action:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _flashlightBtn;
}

- (void)flashlightBtn_action:(UIButton *)button {
    if (button.selected == NO) {
        [scanCode turnOnFlashlight];
        self.isSelectedFlashlightBtn = YES;
        button.selected = YES;
    }
    else {
        [self removeFlashlightBtn];
    }
}

- (void)removeFlashlightBtn {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self->scanCode turnOffFlashlight];
        self.isSelectedFlashlightBtn = NO;
        self.flashlightBtn.selected = NO;
        [self.flashlightBtn removeFromSuperview];
    });
}

- (void)setupNavigationBar {
    // 添加左上角返回按钮
    UIButton *scanBackButton = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(13.0f) frame:CGRectMake(KScaleWidth(15.0f), kNavagationBarH - KScaleWidth(33.0f), KScaleWidth(33.0f), KScaleWidth(33.0f)) title:@"" titleColor:kColorHEX(0xC4C3C3) image:@"back_icon_white"];
    [scanBackButton addTarget:self action:@selector(scanBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBackButton];
    
}

- (void)scanBackButton:(UIButton *)button {
    [self.scanView stopScanning];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Delegate

#pragma mark - SetupUI
- (void)creatUI {
    
    self.view.backgroundColor = [UIColor blackColor];

    scanCode = [XMScanCodeObc scanCode];
    
    [self setupQRCodeScan];
    
    [self.view addSubview:self.scanView];
    [self.view addSubview:self.promptLabel];
    /// 为了 UI 效果
    [self.view addSubview:self.bottomView];
    [self setupNavigationBar];
}

- (void)setupQRCodeScan {
    BOOL isCameraDeviceRearAvailable = scanCode.isCameraDeviceRearAvailable;
    if (isCameraDeviceRearAvailable == NO) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    scanCode.openLog = YES;
    scanCode.brightness = YES;

    [scanCode scanWithController:self resultBlock:^(XMScanCodeObc *scanCode, NSString *result) {
        if (result) {
            // 识别成功
            [scanCode stopRunning];
            // 扫描一维码 请求/v1.0/goods/goodsMarketing  商品类型是普通品加入购物车 营销品跳转商品详情
            
        }
    }];
    
    [scanCode scanWithBrightnessBlock:^(XMScanCodeObc *scanCode, CGFloat brightness) {
        if (brightness < - 1) {
            [weakSelf.view addSubview:weakSelf.flashlightBtn];
        } else {
            if (weakSelf.isSelectedFlashlightBtn == NO) {
                [weakSelf removeFlashlightBtn];
            }
        }
    }];
}

#pragma mark - Getter
- (XMScanCodeView *)scanView {
    if (!_scanView) {
        _scanView = [[XMScanCodeView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }
    return _scanView;
}

- (UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.backgroundColor = [UIColor clearColor];
        CGFloat promptLabelX = 0;
        CGFloat promptLabelY = 0.73 * self.view.frame.size.height;
        CGFloat promptLabelW = self.view.frame.size.width;
        CGFloat promptLabelH = 25;
        _promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
        _promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
        _promptLabel.text = @"将二维码/条码放入框内, 即可自动扫描";
    }
    return _promptLabel;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.scanView.frame), self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(self.scanView.frame))];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
